package com.crm.miaohe.app.controller;


import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.crm.miaohe.app.service.WxService;
import com.crm.miaohe.app.utils.WxUtil;

@RestController
@RequestMapping("/api/app/weixin")
public class WxInitController {

    protected Logger _logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WxService wxService;

    /**
     *@Author: hdx
     *@CreateTime: 20:39 2020/2/14
     *@param:  shareUrl 分享url地址
     *@Description: 初始化微信JSSDK Config信息
    1.先通过appId和appSecret参数请求指定微信地址 获取AccessToken
    2.在通过第一步中的AccessToken作为参数请求微信地址 获取jsapi_ticket临时票据(此处不考虑调用频率，使用者根据情况放入缓存或定时任务)
    3.通过第二步的JssdkGetticket和timestamp,nonceStr,url作为参数请求微信地址，获取签名signature
    4.将第三步获得的signature和jsapi_ticket,nonceStr,timestamp,url返回给前端，作为Config初始化验证的信息
     */
    @PostMapping("/initWXJSSDKConfigInfo")
    public ResponseEntity<String> initWXJSConfig (@RequestBody Map<String,Object> map) throws Exception{
        String url = map.get("url").toString();
        _logger.info("url=" + url);
        String json = "";
        Map<String,String> data = null;
        try {
            data = wxService.initJSSDKConfig(url);
            json = WxUtil.mapToJson(data);
        }catch (Exception e){
        	ResponseEntity.ok(e.getMessage());
        }
        return ResponseEntity.ok(json);
    }

    @PostMapping("/openid")
    public ResponseEntity<String> get(@RequestBody Map<String,Object> map) {
    	 Map<String,String> data = null;
    	 String json = "";
         try {
             data = wxService.getOpenId(map);
             json = WxUtil.mapToJson(data);
         }catch (Exception e){
         	ResponseEntity.ok(e.getMessage());
         }
         return ResponseEntity.ok(json);
    }
    
    @GetMapping("/verify")
    public String get(@RequestParam String url) {
       return url;
    }

}

